<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';

import * as echarts from 'echarts';

import { getCombinedMonthlyStats, getCombinedStats } from '#/api/eventMon';
import lishi from '#/assets/images/lishi.png';
import redian from '#/assets/images/redian.png';
import Zhandian from '#/assets/images/zhandianshuju.png';
import zhishiku from '#/assets/images/zhishiku.png';

import Slot from './Slot.vue';

const statsData = ref({
  siteData: { count: 0, title: '站点数据', icon: Zhandian },
  historyData: { count: 0, title: '历史数据', icon: lishi },
  knowledge: { count: 0, title: '知识库', icon: zhishiku },
  hotEvent: { count: 0, title: '热点事件', icon: redian },
});

const trendData = ref({
  months: [],
  siteTrend: [],
  knowledgeTrend: [],
});

let chartInstance = null;

// 生成最近6个月的月份标签
function generateMonthLabels() {
  const months = [];
  const date = new Date();
  const formatter = new Intl.DateTimeFormat('zh-CN', {
    month: 'numeric',
    day: 'numeric',
  });

  for (let i = 5; i >= 0; i--) {
    const tempDate = new Date(date);
    tempDate.setMonth(date.getMonth() - i);
    months.push(formatter.format(tempDate));
  }
  return months;
}

onMounted(async () => {
  try {
    // 获取统计数据
    const statsRes = await getCombinedStats();
    statsData.value = {
      siteData: {
        ...statsData.value.siteData,
        count: statsRes.siteDataCount || 0,
      },
      historyData: {
        ...statsData.value.historyData,
        count: 0,
      },
      knowledge: {
        ...statsData.value.knowledge,
        count: statsRes.knowledgeBaseCount || 0,
      },
      hotEvent: {
        ...statsData.value.hotEvent,
        count: 0,
      },
    };

    // 获取趋势数据
    const trendRes = await getCombinedMonthlyStats();
    trendData.value = {
      months: generateMonthLabels(),
      siteTrend: trendRes.siteStats || [],
      knowledgeTrend: trendRes.knowledgeBaseStats || [],
    };

    initChart();
  } catch (error) {
    console.error('获取数据失败:', error);
  }
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

function initChart() {
  const chartDom = document.querySelector('#trend-chart');
  if (!chartDom) return;

  chartInstance = echarts.init(chartDom);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter: (params) => {
        return `${params[0].axisValue}<br/>
                ${params[0].marker} ${params[0].seriesName}: ${params[0].value}<br/>
                ${params[1].marker} ${params[1].seriesName}: ${params[1].value}`;
      },
    },
    legend: {
      data: ['站点数据', '知识库'],
      textStyle: {
        color: '#8eaabe',
      },
      right: 10,
      top: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
      top: '15%',
    },
    xAxis: {
      type: 'category',
      data: trendData.value.months,
      axisLine: {
        lineStyle: {
          color: '#8eaabe',
        },
      },
      axisLabel: {
        color: '#8eaabe',
        interval: 0,
        rotate: 30,
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#8eaabe',
        },
      },
      axisLabel: {
        color: '#8eaabe',
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(142, 170, 190, 0.2)',
        },
      },
    },
    series: [
      {
        name: '站点数据',
        type: 'line',
        smooth: true,
        data: trendData.value.siteTrend,
        itemStyle: {
          color: '#2a82e4',
        },
        lineStyle: {
          width: 3,
        },
        symbol: 'circle',
        symbolSize: 8,
        emphasis: {
          itemStyle: {
            color: '#2a82e4',
            borderColor: '#fff',
            borderWidth: 2,
          },
        },
      },
      {
        name: '知识库',
        type: 'line',
        smooth: true,
        data: trendData.value.knowledgeTrend,
        itemStyle: {
          color: '#ff8d1a',
        },
        lineStyle: {
          width: 3,
        },
        symbol: 'circle',
        symbolSize: 8,
        emphasis: {
          itemStyle: {
            color: '#ff8d1a',
            borderColor: '#fff',
            borderWidth: 2,
          },
        },
      },
    ],
  };

  chartInstance.setOption(option);

  const resizeHandler = () => chartInstance && chartInstance.resize();
  window.addEventListener('resize', resizeHandler);

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler);
  });
}
</script>

<template>
  <div class="wrap">
    <Slot>
      <template #header>
        <span>数据采集分析</span>
      </template>
      <template #com>
        <a-select v-model:value="selectValue" style="width: 120px">
          <a-select-option value="0">全部</a-select-option>
          <a-select-option value="1">Lucy</a-select-option>
          <a-select-option value="2">Lucy</a-select-option>
        </a-select>
      </template>
      <template #content>
        <div class="stats-grid">
          <div class="stat-item" v-for="(item, key) in statsData" :key="key">
            <img :src="item.icon" class="stat-icon" />
            <div class="stat-info">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.count }}</div>
            </div>
          </div>
        </div>

        <!-- 折线图容器 -->
        <div id="trend-chart" class="trend-chart"></div>
      </template>
    </Slot>
  </div>
</template>

<style scoped>
.wrap {
  width: 100%;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  padding: 16px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 12px;
}

.stat-info {
  text-align: center;
}

.stat-title {
  font-size: 16px;
  color: rgb(142, 170, 190);
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #fdfdfd;
}

.trend-chart {
  width: 100%;
  height: 290px;
  margin-top: -10px;
  background: rgba(10, 16, 21, 0.5);
  border-radius: 8px;
  padding: 15px;
}
</style>
